<template>
  <el-dialog
    v-model="editDialogVisible"
    title="编辑文章"
    width="60%"
    center
    @close="closeEditDialog(false)"
  >
    <el-form
      :rules="rules"
      :model="form"
      label-width="100px"
      ref="validateForm"
    >
      <el-form-item label="文章标题" prop="article_title">
        <el-input v-model="form.article_title" />
      </el-form-item>
      <el-form-item label="文章分类" prop="category_id">
        <el-input v-model="form.category_id" />
      </el-form-item>
      <el-form-item label="文章图片" prop="article_picture">
        <el-upload
          class="avatar-uploader"
          :action="uploadURL"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章详情" prop="article_content">
        <QuillEditor theme="snow" ref="editor"></QuillEditor>
      </el-form-item>
      <!-- <el-form-item>
        <el-button type="primary" @click="submit(data)">添加商品</el-button>
      </el-form-item> -->
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <!-- 这里不要使用默认的,默认的close不是响应式的 -->
        <el-button
          @click="
            () => {
              closeEditDialog(false)
            }
          "
        >
          取消
        </el-button>
        <el-button type="primary" @click="submitEdit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { reactive, toRefs, ref, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
// 引入富文本编辑器及其样式
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import axios from 'axios'
//2.根据商品ID查询要编辑的商品数据的方法
function useLoadEditData(state, editor) {
  //console.log('文章Id', state.ArticleId)
  axios.get(`/blogArticle/${state.ArticleId}`).then((res) => {
    // console.log(res.data.result.data)
    state.form = res.data.result.data
    state.form.article_picture = res.data.result.data.article_picture
    state.imageUrl =
      import.meta.env.VITE_APP_URL + '/' + res.data.result.data.article_picture
    editor.value.setHTML(res.data.result.data.article_content)
  })
}
//提交编辑好的文章
function useEditData(state, validateForm, editor, emit) {
  const submitEdit = () => {
    state.form.article_content =
      editor.value.getText().replace(/(\r\n|\n|\r)/gm, '<br/>') !== '<br/>'
        ? editor.value.getHTML()
        : ''
    //验证表单的值都填完没有
    validateForm.value.validate((valid) => {
      //console.log(valid) //如果有没填的就是false,都填了就是true
      //获取表单数据
      //console.log(state.ArticleId)
      //console.log(state.form.article_picture) ///images/测试图片_539.jpg
      //console.log(state.form.article_title)
      if (valid) {
        const obj = {
          article_title: state.form.article_title,
          category_id: state.form.category_id,
          article_picture: state.form.article_picture,
          article_content: state.form.article_content,
        }
        //console.log('数据', obj)
        axios.put(`/blogArticle/${state.ArticleId}`, obj).then((res) => {
          console.log(res)
          // // 关闭表单
          emit('onCloseEditDialog', false, res.data)
        })
      }
    })
  }
  return {
    submitEdit,
  }
}
//
export default {
  components: {
    QuillEditor,
  },
  props: {
    editDialogVisible: Boolean,
    ArticleId: Number,
  },
  emits: ['onCloseEditDialog'],
  setup(props, { emit }) {
    const validateForm = ref()
    const editor = ref()
    const pic = ref()
    const state = reactive({
      editDialogVisible: props.editDialogVisible,
      ArticleId: props.ArticleId,
      uploadURL: import.meta.env.VITE_APP_URL + '/upload',
      imageUrl: '',
      form: {
        article_title: '',
        category_id: '',
        article_picture: '',
        article_content: '',
      },
    })
    // 上传成功以后的处理函数
    const handleAvatarSuccess = (response) => {
      state.imageUrl = import.meta.env.VITE_APP_URL + '/' + response.msg
      pic.value = response.msg
      //console.log('图片', pic.value)
      state.form.article_picture = response.msg
      //console.log(state.form.article_picture)
    }
    const closeEditDialog = (visible) => {
      // 使用父组件的方法,方法名,传递的参数
      emit('onCloseEditDialog', visible)
    }
    // 校验规则
    const rules = {
      article_title: [
        { required: true, message: '文章标题不能为空', trigger: 'blur' },
      ],
      category_id: [
        { required: true, message: '文章分类不能为空', trigger: 'blur' },
      ],
      article_picture: [
        { required: true, message: '文章图片不能为空', trigger: 'blur' },
      ],
      article_content: [
        { required: true, message: '文章详情不能为空', trigger: 'blur' },
      ],
    }

    // 接收要打印的文章编号
    onMounted(() => {
      //console.log('文章Id', state.ArticleId)
      //1.挂载的时候,根据商品ID查询要编辑的商品数据
      //注意:富文本编辑器的值要另外传递
      useLoadEditData(state, editor)
    })
    return {
      ...toRefs(state),
      ...useEditData(state, validateForm, editor, emit),
      closeEditDialog,
      rules,
      handleAvatarSuccess,
      validateForm,
      editor,
    }
  },
}
</script>

<style>
.el-form-item__content {
  display: block;
}
/* 图片上传样式 */
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
/* 设置图片上传宽高 */
.avatar {
  width: 100px;
  height: 100px;
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
}
</style>
